package me.zhengjie.modules.wrap;

import cn.hutool.http.server.HttpServerResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BodyWrapperFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        CustomHttpServletRequestWrapper requestWrapper = null;
//        CustomHttpServletResponseWrapper customHttpServletResponseWrapper = null;

        if (servletRequest instanceof HttpServletRequest) {
            requestWrapper = new CustomHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        }

//        if (servletResponse instanceof HttpServletResponse) {
//            customHttpServletResponseWrapper = new CustomHttpServletResponseWrapper((HttpServletResponse) servletResponse);
//        }

        filterChain.doFilter(
                requestWrapper == null ? servletRequest : requestWrapper,
//                customHttpServletResponseWrapper == null ? servletResponse : customHttpServletResponseWrapper
                servletResponse
        );

//        String result = customHttpServletResponseWrapper.getContent();
//
//        System.out.println("返回结果: " + result);
//
//        servletResponse.setContentLength(-1);
//        servletResponse.getWriter().write(result);
    }

    @Override
    public void destroy() {

    }
}
